define(["queryPopup"], function (queryPopup) {

	/**绘制圆角矩形*/
	var drawRectround = function (ctx, x, y, width, height, radius, color, type) {
		ctx.beginPath();
		ctx.moveTo(x, y + radius);
		ctx.lineTo(x, y + height - radius);
		ctx.quadraticCurveTo(x, y + height, x + radius, y + height);
		ctx.lineTo(x + width - radius, y + height);
		ctx.quadraticCurveTo(x + width, y + height, x + width, y + height - radius);
		ctx.lineTo(x + width, y + radius);
		ctx.quadraticCurveTo(x + width, y, x + width - radius, y);
		ctx.lineTo(x + radius, y);
		ctx.quadraticCurveTo(x, y, x, y + radius);
		ctx[type + 'Style'] = color || params.color;
		ctx.closePath();
		ctx[type]();
	};

	L.IsonlineLayer = L.Layer.extend({
		includes: L.Mixin.Events,

		options: {
			showLabel: true,
			opacity: 1,
			weight: 1,
			zindex: 60,
			type: null,
			linecolor: "#ff7800",
			fontcolor: "rgba(255,255,255,1)",
			bgcolor: "rgba(239,126,6,0.6)",
			fontsize: 20, //10
			radius: 10, //5
			generalization: 0, //概化参数
			tension: 0.4, //张量
			grain: 20, //密度
			pointnum: 5, //等值线点数大于此值标注
			showpoint: false,
			Max: null,
			Min: null,
			urlLog: false
		},

		initialize: function (options) {
			L.setOptions(this, options);
		},

		onAdd: function (map) {
			this._map = map;
			if (!this._container) {
				this._initCanvas();
			}
			map._panes.overlayPane.appendChild(this._container);
			map.on('zoomstart', this._clearCanvas, this);
			map.on('moveend', this._reset, this);
			if (map.options.zoomAnimation && L.Browser.any3d) {
				map.on('zoomanim', this._animateZoom, this);
			}
			this._reset();
		},

		/**在设置里更改颜色后重绘*/
		_redraw: function (color, weight) {
			var self = this;
			self.options.linecolor = color;
			self.options.weight = weight;
			self._reset();
		},

		onRemove: function (map) {
			map.getPanes().overlayPane.removeChild(this._container);
			map.off('zoomstart', this._clearCanvas, this);
			map.off('moveend', this._reset, this);
			if (map.options.zoomAnimation) {
				map.off('zoomanim', this._animateZoom, this);
			}
		},

		addTo: function (map) {
			map.addLayer(this);
			return this;
		},

		getAttribution: function () {
			return this.options.attribution;
		},

		_setZindex: function (Zindex) {
			this._container.style.zIndex = Zindex;
		},

		_initCanvas: function () {
			this._container = L.DomUtil.create('div', 'leaflet-image-layer');
			this._canvas = L.DomUtil.create('canvas', '');
			this._setZindex(this.options.zindex);

			if (this._map.options.zoomAnimation && L.Browser.any3d) {
				L.DomUtil.addClass(this._canvas, 'leaflet-zoom-animated');
			} else {
				L.DomUtil.addClass(this._canvas, 'leaflet-zoom-hide');
			}

			this._container.appendChild(this._canvas);
			L.extend(this._canvas, {
				onselectstart: L.Util.falseFn,
				onmousemove: L.Util.falseFn,
				onload: L.bind(this._onCanvasLoad, this)
			});
		},

		_animateZoom: function (e) {
			var map = this._map,
				container = this._container,
				canvas = this._canvas,
				scale = map.getZoomScale(e.zoom),
				nw = map.containerPointToLatLng([0, 0]),
				se = map.containerPointToLatLng([canvas.width, canvas.height]),
				topLeft = map._latLngToNewLayerPoint(nw, e.zoom, e.center),
				size = map._latLngToNewLayerPoint(se, e.zoom, e.center)._subtract(topLeft),
				origin = topLeft._add(size._multiplyBy(1 / 2 * (1 - 1 / scale)));
		},

		_reset: function () {
			var container = this._container,
				canvas = this._canvas,
				size = this._map.getSize(),
				lt = this._map.containerPointToLayerPoint([0, 0]);
			L.DomUtil.setPosition(container, lt);
			container.style.width = size.x + 'px';
			container.style.height = size.y + 'px';
			canvas.width = size.x * 2;
			canvas.height = size.y * 2;
			canvas.style.width = size.x + 'px';
			canvas.style.height = size.y + 'px';
			this.__draw(this.features);
		},

		_onCanvasLoad: function () {
			this.fire('load');
		},

		/**设置最大最小值*/
		_setMaxMin: function (max, min) {
			this.options.Max = max;
			this.options.Min = min;
		},

		/**设置数据*/
		_setdata: function () {
			var self = this;
			var tlid = showTimebarLoading();
			var pressUrl = Config.dataPath + "/" + Config.currentDrawTime + "/press_E_full.json";
			if (!Config.ImgData[pressUrl]) {
				(function (ctim, url, tlid) {
					if (self.options.urlLog === true)
						console.log("0000 开始请求网络数据：" + url);
					$.getJSON(url).done(function (result) {
						if (self.options.urlLog === true)
							console.log("0001 获取到网络数据：" + url);
						Config.ImgData[url] = result;
						if (ctim === Config.currentDrawTime) {
							var features = result.features;
							self.features = features;
							self.__draw(features);
							if (self.options.urlLog === true)
								console.log("0002 绘制网络数据：" + url);
						} else {
							if (self.options.urlLog === true)
								console.log("0003 拦截网络数据绘制：" + url);
						}
						hideLayerLoading("pres", tlid);
					}).fail(function () {
						url = url.replace("press_E_full", "press_G_full");
						if (self.options.urlLog === true)
							console.log("0000 开始请求网络数据：" + url);
						$.getJSON(url).done(function (result) {
							if (self.options.urlLog === true)
								console.log("0001 获取到网络数据：" + url);
							Config.ImgData[url] = result;
							if (ctim === Config.currentDrawTime) {
								var features = result.features;
								self.features = features;
								self.__draw(features);
								if (self.options.urlLog === true)
									console.log("0002 绘制网络数据：" + url);
							} else {
								if (self.options.urlLog === true)
									console.log("0003 拦截网络数据绘制：" + url);
							}
							hideLayerLoading("pres", tlid);
						}).fail(function () {
							hideLayerLoading("pres", tlid);
							alert("当前时刻无气压数据");
						});
					});
				})(Config.currentDrawTime, pressUrl, tlid);
			} else {
				(function (ctim, url, tlid) {
					if (self.options.urlLog === true)
						console.log("0004 获取到缓存数据：" + url);
					if (ctim === Config.currentDrawTime) {
						var features = Config.ImgData[url].features;
						self.features = features;
						self.__draw(features);
						if (self.options.urlLog === true)
							console.log("0005 绘制缓存数据：" + url);
					} else {
						if (self.options.urlLog === true)
							console.log("0006 拦截缓存数据绘制：" + url);
					}
					hideLayerLoading("pres", tlid);
				})(Config.currentDrawTime, pressUrl, tlid);
			}
		},

		__draw: function (features) {
			var self = this,
				canvas = this._canvas,
				map = this._map;
			if (!features) {
				console.log("nodata");
				return;
			}
			if (L.Browser.canvas && map) {
				this.currentzoom = map.getZoom();
				var arr, i, isin1000, minva, va, _feas;
				if (this.currentzoom <= 5) { //抽稀等值线
					arr = [];
					for (i = 0; i < features.length; i++) {
						va = features[i].properties.value;
						arr.push(va);
					}
					minva = Math.min.apply(null, arr);
					_feas = [];
					for (i = 0; i < features.length; i++) {
						va = features[i].properties.value;
						isin1000 = (va - minva) / 100;
						if (isin1000 % 4 === 0) {
							_feas.push(features[i]);
						}
					}
					features = _feas;
				}
				this.currentbounds = map.getBounds();
				this.leftup = this.currentbounds.getNorthWest();
				this.rightdown = this.currentbounds.getSouthEast();
				var Cwidth = canvas.clientWidth;
				var Cheight = canvas.clientHeight;
				var ctx = canvas.getContext("2d");
				this.width = Cwidth;
				this.height = Cheight;
				ctx.clearRect(0, 0, Cwidth * 2, Cheight * 2);

				var lineobj;
				var isclose;

				for (i = 0; i < features.length; i++) {
					isclose = false;
					var simplified = features[i];
					var line = simplified.geometry.coordinates;
					lineobj = null;
					var lineArr = [];
					for (var j = 0; j < line.length; j++) {
						var laln = L.latLng(line[j][1], line[j][0]);
						lineArr.push(laln);
					}
					if (lineArr[0].lat === lineArr[lineArr.length - 1].lat && lineArr[0].lng === lineArr[lineArr.length - 1].lng) {
						isclose = true;
					}
					lineobj = L.polyline(lineArr);
					var bou = lineobj.getBounds();
					var isin = this.currentbounds.intersects(bou);
					if (isin) {
						var InScreenpoint = new Array();
						var len = simplified.geometry.coordinates.length;
						var pointArr = [];
						for (var p = 0; p < len; p++) {
							var Inpoint = L.latLng(simplified.geometry.coordinates[p][1], simplified.geometry.coordinates[p][0]);
							if (this.currentbounds.contains(Inpoint)) {
								InScreenpoint.push(p);
							}

							var screenpoint = map.latLngToContainerPoint(Inpoint);
							pointArr.push(screenpoint.x * 2);
							pointArr.push(screenpoint.y * 2);
						}
						ctx.lineWidth = self.options.weight * 2;
						ctx.beginPath();
						ctx.moveTo(pointArr[0], pointArr[1]);
						if (isclose === true) {
							pointArr.pop();
							pointArr.pop();
							ctx.curve(pointArr, this.options.tension, this.options.grain, true);
						} else {
							ctx.curve(pointArr, this.options.tension, this.options.grain, false);
						}
						ctx.strokeStyle = this.options.linecolor;
						ctx.stroke();

						if (this.options.showLabel === true) {
							if (line.length > this.options.pointnum) {
								try {
									if (InScreenpoint.length === 0)
										continue;
									var center = InScreenpoint[parseInt(InScreenpoint.length / 2)];
									var x = line[center][0];
									var y = line[center][1];
									var screenp = map.latLngToContainerPoint(L.latLng(y, x));
									screenp.x = screenp.x * 2;
									screenp.y = screenp.y * 2;
									var txt = " ";
									switch (this.options.type) {
										case "pres":
											txt = simplified.properties.value;
											txt = " " + (parseInt(txt) / 100).toString() + "hPa ";
											break;
										case "wave":
											txt = parseInt(simplified.properties.value);
											txt = " " + txt + "m ";
											break;
										default:
											txt = simplified.properties.value;
											txt = txt;
									}
									var txtwidth = 85;
									drawRectround(ctx, screenp.x, screenp.y - this.options.fontsize, txtwidth, this.options.fontsize + 4, this.options.radius, this.options.bgcolor, "fill");
									ctx.font = this.options.fontsize + "px 微软雅黑";
									ctx.fillStyle = this.options.fontcolor;
									ctx.textAlign = "center";
									ctx.fillText(txt, screenp.x + txtwidth / 2, screenp.y);
								} catch (e) {
									console.log(e);
								}
							}
						}
					}
				}

				queryPopup.changePopupQueryRes();

			}
		},

		_latLngToCanvasPoint: function (latlng) {
			var map = this._map;
			var projectedPoint = map.project(L.latLng(latlng));
			projectedPoint._subtract(map.getPixelOrigin());
			return L.point(projectedPoint).add(map._getMapPanePos());
		},

		_clearCanvas: function () {
			var canvas = this._canvas;
			try {
				var Cwidth = canvas.clientWidth;
				var Cheight = canvas.clientHeight;
				var ctx = canvas.getContext("2d");
				ctx.clearRect(0, 0, Cwidth * 2, Cheight * 2);
			} catch (e) {
				console.log(e);
			}
		}

	});

	return function (options) {
		return new L.IsonlineLayer(options);
	};
});